<template>
    <div class="white-box">
        <cell-tip
            tip="创建需求功能为用户提供产品需求收集，帮助您改善使用体验。如您有业务咨询、问题反馈、投诉建议等，可直接拨打客服热线：0871-63177163"
        />
        <div class="dem-box">
            <h2>创建需求</h2>
            <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="160px">
                <el-form-item label="需求名称" prop="names">
                    <el-input v-model.trim="ruleForm.names" clearable placeholder="请输入需求名称" />
                </el-form-item>
                <el-form-item label="需求场景" prop="dem_scene">
                    <div class="editor-box">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorSceneRef" :defaultConfig="toolbarConfig" mode="default" />
                        <Editor
                            style="height: 320px; overflow-y: hidden"
                            v-model="ruleForm.dem_scene"
                            :defaultConfig="editorConfig"
                            mode="default"
                            @onCreated="handleCreated"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="需求描述" prop="dem_desc">
                    <div class="editor-box">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorDescRef" :defaultConfig="toolbarConfig" mode="default" />
                        <Editor
                            style="height: 320px; overflow-y: hidden"
                            v-model="ruleForm.dem_desc"
                            :defaultConfig="editorDescConfig"
                            mode="default"
                            @onCreated="handleDescCreated"
                        />
                    </div>
                </el-form-item>
                <el-form-item label="接受额外收费" prop="price">
                    <el-radio-group v-model="ruleForm.price">
                        <el-radio label="1" size="large">是</el-radio>
                        <el-radio label="2" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="接受定制" prop="diy">
                    <el-radio-group v-model="ruleForm.diy">
                        <el-radio label="1" size="large">是</el-radio>
                        <el-radio label="2" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <div class="foot-btn flexs-center" style="margin-top: 30px">
                        <el-button type="primary" :loading="form_loading" @click="submitForm(ruleRef)">提交需求</el-button>
                        <el-button @click="resetForm(ruleRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>

    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, shallowRef, reactive, onBeforeUnmount } from "vue"
import { useRouter } from "vue-router"
import "@wangeditor/editor/dist/css/style.css"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import CellTip from "@components/cell-tip.vue"
import GoBack from "@components/GoBack.vue"

const router = useRouter()
const { proxy } = getCurrentInstance()

onMounted(() => {})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    ruleRef.value = null

    if (editorSceneRef.value == null) return
    editorSceneRef.value.destroy()

    if (editorDescRef.value == null) return
    editorDescRef.value.destroy()
})

/**
 * 提交需求
 * @param {Boolean} form_loading 弹窗按钮状态
 * @param {Array} ruleRef 表单规则
 * @param {Object} ruleForm  表单字段
 * @param {Object} ruleCheck  表单提示
 */
const form_loading = ref(false)
const ruleRef = ref(null)
const ruleForm = reactive({
    names: "",
    dem_scene: "",
    dem_desc: "",
    price: "",
    diy: "",
})
const ruleCheck = reactive({
    names: [{ required: true, message: "请输入供应价格", trigger: "blur" }],
    dem_scene: [{ required: true, validator: validScene, trigger: "blur" }],
    dem_desc: [{ required: true, validator: validDesc, trigger: "blur" }],
    price: [{ required: true, message: "请选择是否接受额外收费", trigger: "change" }],
    diy: [{ required: true, message: "请选择是否接受定制", trigger: "change" }],
})
// 需求场景-自定义校验规则
function validScene(rule, value, callback) {
    let regu = editorSceneRef.value.getText()
    if (regu === "") {
        callback(new Error("请输入需求场景"))
    } else {
        callback()
    }
}
// 需求描述-自定义校验规则
function validDesc(rule, value, callback) {
    let regu = editorSceneRef.value.getText()
    if (regu === "") {
        callback(new Error("请输入需求描述"))
    } else {
        callback()
    }
}
// 提交表单
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            // 去除图片根域名以及根域名后面的'/'
            let html_scene = ruleForm.dem_scene.replace(/\bhttps?:\/\/(.*?)\/+/gi, "")
            let html_desc = ruleForm.dem_desc.replace(/\bhttps?:\/\/(.*?)\/+/gi, "")

            form_loading.value = true
            let data = {
                product_common_id: ruleForm.comm_id,
            }
            proxy.$axios
                .post("", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: "提交需求成功", type: "success" })
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    editorSceneRef.value.setHtml("<p></p>")
    editorDescRef.value.setHtml("<p></p>")
}

/**
 * 富文本编辑器
 * @param {Object} editorConfig 编辑器配置
 * @param {String} valueHtml 输入内容
 * @param {Object} toolbarConfig 工具栏配置
 * @param {Function} createEditor 创建编辑器
 * @param {Function} createToolbar 创建工具栏
 * @param {Function} handleChange 编辑器内容变化
 */
const editorSceneRef = shallowRef() // 需求场景编辑器实例，必须用 shallowRef
// 排除不需要的菜单
const toolbarConfig = {
    excludeKeys: ["insertLink", "insertImage", "editImage", "viewImageLink", "group-video", "emotion", "fullScreen"],
}
const editorConfig = { placeholder: "输入需求场景...", MENU_CONF: {} }
const handleCreated = (editor) => {
    editorSceneRef.value = editor // 记录 editor 实例，需求场景
}
// 自定义上传，需求场景
editorConfig.MENU_CONF["uploadImage"] = {
    async customUpload(file, insertFn) {
        uploadImgs(file, insertFn)
    },
}

// 需求描述
const editorDescRef = shallowRef() // 编辑器实例，必须用 shallowRef
const editorDescConfig = { placeholder: "输入需求描述...", MENU_CONF: {} }
const handleDescCreated = (editor) => {
    editorDescRef.value = editor
}
editorDescConfig.MENU_CONF["uploadImage"] = {
    async customUpload(file, insertFn) {
        uploadImgs(file, insertFn)
    },
}

// 富文本公用上传图片
function uploadImgs(file, insertFn) {
    let data = new FormData()
    data.append("from", "article")
    data.append("image", file)
    proxy.$axios
        .post("upload/image", data)
        .then((res) => {
            if (res.data.code == 0) {
                let url = proxy.imgUrl + res.data.data.path
                insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "Demand",
}
</script>

<style lang="less" scoped>
.editor-box {
    border: 1px solid #ccc;
    border-radius: 2px;
}
.dem-box {
    margin-top: @margin-base * 10;
    h2 {
        margin-bottom: @margin-xl;
    }
    .foot-btn {
        left: 103px;
    }
}
</style>